"""用户点赞功能模块"""
import json, os, time
from datetime import datetime
from typing import Dict, Optional
from pydantic import BaseModel, Field

class LikeRequest(BaseModel): conversation_id: str = Field(..., description="会话ID"); user_query: Optional[str] = Field(None, description="用户查询内容"); phone_number: Optional[str] = Field(None, description="用户手机号")

class LikeManager:
    def __init__(self, data_dir: str = "like_data"):
        self.data_dir = data_dir; self.likes_file = os.path.join(data_dir, "likes.json"); os.makedirs(data_dir, exist_ok=True); self.likes = self._load_data()
    def _load_data(self):
        try:
            if os.path.exists(self.likes_file):
                with open(self.likes_file, 'r', encoding='utf-8') as f: return json.load(f)
        except: pass
        return []
    def _save_data(self):
        try:
            with open(self.likes_file, 'w', encoding='utf-8') as f: json.dump(self.likes, f, ensure_ascii=False, indent=2, default=str)
        except: pass
    def add_like(self, like_request: LikeRequest) -> Dict:
        try:
            if any(like.get('conversation_id') == like_request.conversation_id for like in self.likes):
                return {"status": "success", "message": "您已经点过赞了", "already_liked": True}
            like_record = {"id": f"like_{int(time.time() * 1000)}", "conversation_id": like_request.conversation_id, "user_query": like_request.user_query, "phone_number": like_request.phone_number, "timestamp": datetime.now().isoformat()}
            self.likes.append(like_record); self._save_data()
            return {"status": "success", "message": "点赞成功！感谢您的支持！", "like_id": like_record["id"], "already_liked": False}
        except Exception as e:
            return {"status": "error", "message": f"点赞失败: {str(e)}"}
    def get_like_stats(self):
        total = len(self.likes); today = datetime.now().date()
        today_likes = sum(1 for like in self.likes if datetime.fromisoformat(like['timestamp']).date() == today)
        return {"total_likes": total, "today_likes": today_likes, "last_updated": datetime.now().isoformat()}
    def has_liked(self, conversation_id: str) -> bool:
        return any(like.get('conversation_id') == conversation_id for like in self.likes)

_like_manager = LikeManager()
submit_like = _like_manager.add_like
get_like_statistics = _like_manager.get_like_stats
has_user_liked = _like_manager.has_liked